package com.auto.autoapp.ui.result

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.auto.autoapp.R
import com.auto.autoapp.base.BaseActivity
import com.auto.autoapp.databinding.ActivityResultBinding
import com.auto.autoapp.widgets.SimpleToolbar

/**
 * 简单结果页面：显示由路由参数传入的文本
 */
class ResultActivity : BaseActivity() {
    private lateinit var binding: ActivityResultBinding
    override fun provideView(): View {
        binding = ActivityResultBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun configToolbar(toolbar: SimpleToolbar) {
        super.configToolbar(toolbar)
        toolbar.setTitle("操作结果")
    }

    override fun onInit() {
        val content = intent.getStringExtra(EXTRA_RESULT_TEXT).orEmpty()
        binding.tvResult.text = content
    }

    companion object {
        private const val EXTRA_RESULT_TEXT = "extra_result_text"

        /**
         * 封装的打开方法：支持从 Service 调用（自动添加 FLAG_ACTIVITY_NEW_TASK）
         */
        fun open(context: Context, text: String) {
            val appCtx = context.applicationContext
            val intent = Intent(appCtx, ResultActivity::class.java).apply {
                putExtra(EXTRA_RESULT_TEXT, text)
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
            }
            try {
                if (Looper.myLooper() == Looper.getMainLooper()) {
                    appCtx.startActivity(intent)
                } else {
                    Handler(Looper.getMainLooper()).post { appCtx.startActivity(intent) }
                }
            } catch (e: Exception) {
                Log.e("ResultActivity", "startActivity failed", e)
            }
        }
    }
}